import 'package:flutter/material.dart';
import 'package:flutter_wan_android/generated/l10n.dart';
import 'package:flutter_wan_android/http/http_exception.dart';
import 'package:flutter_wan_android/init/default_app.dart';

import 'view_state_model.dart';

///
/// 基于ViewStateModel的 List子类
///
abstract class ViewStateListModel<T> extends ViewStateModel {
  /// 页面数据
  List<T> _dataList = [];

  List<T> get dataList => _dataList;

  ///第一次进入页面初始化数据
  initData() async {
    setBusy();
    await refresh(init: true);
  }

  ///
  /// 用于[下拉刷新]或者[只加载一次数据]的业务逻辑
  ///
  Future refresh({bool isBusy = false, bool init = false}) async {
    ///当调用setBusy时，会刷新界面
    if (isBusy) {
      setBusy();
    }

    ///返回的数据集
    List<T> data;
    try {
      data = await loadData();
    } catch (e, s) {
      if (init) {
        _dataList.clear();
      }

      if (e is AppHttpException) {
        setError(e, s);
      } else {
        BuildContext context = navigatorKey.currentState.overlay.context;
        AppHttpException exception = AppHttpException(
          HttpErrorType.defaultError,
          message: S.of(context).requestError,
          errorMessage: S.of(context).requestError,
        );
        setError(exception, s);
      }

      return null;
    }

    if (data == null || data.isEmpty) {
      _dataList.clear();
      setEmpty();
    } else {
      onCompleted(data);
      _dataList.clear();
      _dataList.addAll(data);
      setIdle();
    }
  }

  /// 加载数据
  Future<List<T>> loadData();

  ///
  /// 加载完成时回调
  /// data本次加载的数据
  ///
  onCompleted(List<T> data) {}
}
